/*
 * @lc app=leetcode.cn id=235 lang=javascript
 *
 * [235] 二叉搜索树的最近公共祖先
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    while(root){
        if(p.val<root.val&&q.val<root.val){
            root=root.left
        }
        if(p.val>root.val&&q.val>root.val){
            root=root.right
        }
        if((p.val<=root.val&&q.val>=root.val)||(p.val>=root.val&&q.val<=root.val)){
            return root
        }
    }
};
// @lc code=end

var lowestCommonAncestor = function(root, p, q) {
    if((p.val<=root.val&&q.val>=root.val)||(p.val>=root.val&&q.val<=root.val))return root
    if(p.val<root.val&&q.val<root.val){
       return  lowestCommonAncestor(root.left,p,q)
    }if(p.val>root.val&&q.val>root.val){
        return lowestCommonAncestor(root.right,p,q)
    }
    
};